package com.nbcio.im.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbcio.im.core.ImGroup;
import com.nbcio.im.core.ImGroupMember;
import com.nbcio.im.core.mapper.ImGroupMapper;
import com.nbcio.im.core.service.ImGroupService;
import com.nbcio.im.core.service.ImGroupMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * IM群组服务实现类
 *
 * @author nbacheng
 */
@Service
public class ImGroupServiceImpl extends ServiceImpl<ImGroupMapper, ImGroup> implements ImGroupService {
    
    @Autowired
    private ImGroupMemberService imGroupMemberService;
    
    @Override
    public boolean isMember(String groupId, Long userId) {
        LambdaQueryWrapper<ImGroupMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ImGroupMember::getGroupId, groupId)
               .eq(ImGroupMember::getUserId, userId)
               .eq(ImGroupMember::getEnabled, 1)
               .eq(ImGroupMember::getTenantId, "000000");
        
        return imGroupMemberService.count(wrapper) > 0;
    }
    
    @Override
    public LocalDateTime getJoinTime(String groupId, Long userId) {
        LambdaQueryWrapper<ImGroupMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ImGroupMember::getGroupId, groupId)
               .eq(ImGroupMember::getUserId, userId)
               .eq(ImGroupMember::getEnabled, 1)
               .eq(ImGroupMember::getTenantId, "000000");
        
        ImGroupMember member = imGroupMemberService.getOne(wrapper);
        return member != null ? member.getJoinTime() : null;
    }
    
    @Override
    public List<ImGroupMember> getGroupMembers(String groupId) {
        LambdaQueryWrapper<ImGroupMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ImGroupMember::getGroupId, groupId)
               .eq(ImGroupMember::getEnabled, 1)
               .eq(ImGroupMember::getTenantId, "000000")
               .orderByAsc(ImGroupMember::getJoinTime);
        
        return imGroupMemberService.list(wrapper);
    }
}